'use client'

import React, { useState } from 'react'
import { Form, Input, Button, Card, message, Row, Col, Divider } from 'antd'
import { UserOutlined, MailOutlined, LockOutlined, PhoneOutlined, BankOutlined, TeamOutlined } from '@ant-design/icons'
import { USER_FORM_FIELDS, validateUserForm, getUserFieldRules } from '../schemas/userSchema'
import { createEmptyUserForm, formDataToUser } from '../types/user'
import { handleApiError, showSuccess } from '../utils/errorHandler'

const { TextArea } = Input

export default function RegisterForm({ onSuccess, onSwitchToLogin }) {
    const [form] = Form.useForm()
    const [loading, setLoading] = useState(false)
    const [formData, setFormData] = useState(createEmptyUserForm())

    // 处理表单值变化
    const handleValuesChange = (changedValues, allValues) => {
        setFormData(allValues)
    }

    // 处理表单提交
    const handleSubmit = async (values) => {
        setLoading(true)

        try {
            // 前端验证
            const validation = validateUserForm(values)
            if (!validation.isValid) {
                Object.keys(validation.errors).forEach(field => {
                    message.error(validation.errors[field])
                })
                return
            }

            // 转换表单数据
            const userData = formDataToUser(values)

            // 调用注册 API
            const response = await fetch('/api/auth/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    ...userData,
                    password: values.password
                })
            })

            const result = await response.json()

            if (!response.ok) {
                throw new Error(result.message || '注册失败')
            }

            showSuccess('注册成功！欢迎使用产品展示平台')
            form.resetFields()

            if (onSuccess) {
                onSuccess(result.user)
            }

        } catch (error) {
            console.error('Registration error:', error)
            handleApiError(error, '注册失败')
        } finally {
            setLoading(false)
        }
    }

    return (
        <Card
            title="用户注册"
            className="max-w-2xl mx-auto"
            extra={
                onSwitchToLogin && (
                    <Button type="link" onClick={onSwitchToLogin}>
                        已有账户？立即登录
                    </Button>
                )
            }
        >
            <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
                onValuesChange={handleValuesChange}
                initialValues={createEmptyUserForm()}
                className="space-y-4"
            >
                {/* 基本信息 */}
                <Row gutter={16}>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="username"
                            label={USER_FORM_FIELDS.username.label}
                            rules={getUserFieldRules('username')}
                        >
                            <Input
                                prefix={<UserOutlined />}
                                placeholder={USER_FORM_FIELDS.username.placeholder}
                                maxLength={USER_FORM_FIELDS.username.maxLength}
                                showCount
                                size="large"
                            />
                        </Form.Item>
                    </Col>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="email"
                            label={USER_FORM_FIELDS.email.label}
                            rules={getUserFieldRules('email')}
                        >
                            <Input
                                prefix={<MailOutlined />}
                                placeholder={USER_FORM_FIELDS.email.placeholder}
                                maxLength={USER_FORM_FIELDS.email.maxLength}
                                size="large"
                            />
                        </Form.Item>
                    </Col>
                </Row>

                {/* 密码信息 */}
                <Row gutter={16}>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="password"
                            label={USER_FORM_FIELDS.password.label}
                            rules={getUserFieldRules('password')}
                        >
                            <Input.Password
                                prefix={<LockOutlined />}
                                placeholder={USER_FORM_FIELDS.password.placeholder}
                                maxLength={USER_FORM_FIELDS.password.maxLength}
                                size="large"
                            />
                        </Form.Item>
                    </Col>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="confirmPassword"
                            label={USER_FORM_FIELDS.confirmPassword.label}
                            rules={getUserFieldRules('confirmPassword', formData)}
                        >
                            <Input.Password
                                prefix={<LockOutlined />}
                                placeholder={USER_FORM_FIELDS.confirmPassword.placeholder}
                                size="large"
                            />
                        </Form.Item>
                    </Col>
                </Row>

                {/* 个人信息 */}
                <Form.Item
                    name="fullName"
                    label={USER_FORM_FIELDS.fullName.label}
                    rules={getUserFieldRules('fullName')}
                >
                    <Input
                        prefix={<UserOutlined />}
                        placeholder={USER_FORM_FIELDS.fullName.placeholder}
                        maxLength={USER_FORM_FIELDS.fullName.maxLength}
                        showCount
                        size="large"
                    />
                </Form.Item>

                {/* 机构信息 */}
                <Row gutter={16}>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="organization"
                            label={USER_FORM_FIELDS.organization.label}
                            rules={getUserFieldRules('organization')}
                        >
                            <Input
                                prefix={<BankOutlined />}
                                placeholder={USER_FORM_FIELDS.organization.placeholder}
                                maxLength={USER_FORM_FIELDS.organization.maxLength}
                                size="large"
                            />
                        </Form.Item>
                    </Col>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="department"
                            label={USER_FORM_FIELDS.department.label}
                            rules={getUserFieldRules('department')}
                        >
                            <Input
                                prefix={<TeamOutlined />}
                                placeholder={USER_FORM_FIELDS.department.placeholder}
                                maxLength={USER_FORM_FIELDS.department.maxLength}
                                size="large"
                            />
                        </Form.Item>
                    </Col>
                </Row>

                {/* 联系方式 */}
                <Form.Item
                    name="phone"
                    label={USER_FORM_FIELDS.phone.label}
                    rules={getUserFieldRules('phone')}
                >
                    <Input
                        prefix={<PhoneOutlined />}
                        placeholder={USER_FORM_FIELDS.phone.placeholder}
                        maxLength={USER_FORM_FIELDS.phone.maxLength}
                        size="large"
                    />
                </Form.Item>

                {/* 申请理由 */}
                <Form.Item
                    name="applicationReason"
                    label={USER_FORM_FIELDS.applicationReason.label}
                    rules={getUserFieldRules('applicationReason')}
                >
                    <TextArea
                        placeholder={USER_FORM_FIELDS.applicationReason.placeholder}
                        maxLength={USER_FORM_FIELDS.applicationReason.maxLength}
                        showCount
                        rows={USER_FORM_FIELDS.applicationReason.rows}
                        size="large"
                    />
                </Form.Item>

                <Divider />

                {/* 提交按钮 */}
                <Form.Item className="mb-0">
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={loading}
                        size="large"
                        block
                        className="h-12"
                    >
                        <UserOutlined />
                        提交注册申请
                    </Button>
                </Form.Item>

                {/* 提示信息 */}
                <div className="text-center text-gray-500 text-sm mt-4">
                    <p>注册后您可以立即使用平台功能</p>
                </div>
            </Form>
        </Card>
    )
}